package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    WorkspaceService workspaceService;

    /**
     * 营业额统计相关接口
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计相关接口
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);

            Integer totalUser = userMapper.getTotal(map);
            totalUserList.add(totalUser);

            Integer newUser = userMapper.getNewUser(map);
            newUserList.add(newUser);

        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }


    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {

       /* LocalDateTime totalBeginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime totalEndTime = LocalDateTime.of(end, LocalTime.MAX);*/

        List<LocalDate> dateList = new ArrayList();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //添加每日总订单数
            Integer orderCount = getCount(beginTime, endTime, null);
            orderCountList.add(orderCount);
            //添加每日有效订单数
            Integer validOrderCount = getCount(beginTime, endTime, Orders.COMPLETED);
            validOrderCountList.add(validOrderCount);
        }


        //订单总数
        // Integer totalOrderCount = getCount(totalBeginTime, totalEndTime, null);
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //有效订单数
//        Integer validOrderCount =getCount(totalBeginTime, totalEndTime, Orders.COMPLETED);
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = (double) validOrderCount / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排名top10
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> GoodsSalesDTOList = orderMapper.getTop10nameList(beginTime, endTime);
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();

        for (GoodsSalesDTO goodsSalesDTO : GoodsSalesDTOList) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }


    /**
     * 统计订单数量工具类
     *
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getCount(LocalDateTime begin, LocalDateTime end, Integer status) {

        return orderMapper.getCountByTimeAndStatus(begin, end, status);
    }

    /**
     * 导出数据
     */
    public void export(HttpServletResponse response) {
        //30日前 - 昨天的日期
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //获取30天总数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        try {
            XSSFWorkbook excel = new XSSFWorkbook(is); //导入模板
            XSSFSheet sheet = excel.getSheetAt(0); //获得当前sheet
            XSSFRow row = sheet.getRow(1);
            row.getCell(1).setCellValue(begin.toString() + "至" + end.toString());
            row = sheet.getRow(3);//第4行
            row.getCell(2).setCellValue(businessData.getTurnover());//营业额
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());//订单完成率
            row.getCell(6).setCellValue(businessData.getNewUsers());//新增用户数

            row = sheet.getRow(4);//第5行
            row.getCell(2).setCellValue(businessData.getValidOrderCount());//有效订单数
            row.getCell(4).setCellValue(businessData.getUnitPrice());//平均客单价

            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);

                BusinessDataVO data = workspaceService.getBusinessData(
                                LocalDateTime.of(date, LocalTime.MIN),
                                LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());//日期
                row.getCell(2).setCellValue(data.getTurnover());//营业额
                row.getCell(3).setCellValue(data.getValidOrderCount());//有效订单
                row.getCell(4).setCellValue(data.getOrderCompletionRate());//订单完成率
                row.getCell(5).setCellValue(data.getUnitPrice());//平均客单价
                row.getCell(6).setCellValue(data.getNewUsers());//新增用户数
            }

            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            outputStream.flush();
            outputStream.close();
            excel.close();


        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

